package tp.pr3.instructions;

import java.util.StringTokenizer;
import tp.pr3.NavigationModule;
import tp.pr3.RobotEngine;
import tp.pr3.instructions.exceptions.InstructionExecutionException;
import tp.pr3.instructions.exceptions.WrongInstructionFormatException;
import tp.pr3.items.ItemContainer;

public class ScanInstruction
extends java.lang.Object
implements Instruction {
	
	private String itemToScan;
	private ItemContainer robotContainer;
	
	public ScanInstruction()
	{
		itemToScan=null;
		robotContainer=null;
	}
	
	public Instruction parse(java.lang.String cad) throws WrongInstructionFormatException
	{
		StringTokenizer instructionToken = new StringTokenizer(cad);
	    if(instructionToken.countTokens()<1 || instructionToken.countTokens()>2) 
			throw new WrongInstructionFormatException();
		
		String action=instructionToken.nextToken();
		if (!(action.toUpperCase().equalsIgnoreCase("SCAN") || action.toUpperCase().equalsIgnoreCase("ESCANEAR")))
			throw new WrongInstructionFormatException();	
		
		if(instructionToken.countTokens()==1)
			itemToScan=instructionToken.nextToken();
		return this;		
	}
	
	public void execute() throws InstructionExecutionException
	{
		if(robotContainer.numberOfItems()==0)
			throw new InstructionExecutionException("WALL·E says: My inventory is empty\n");
		try
		{
		 if(itemToScan==null)
			{
			System.out.println("WALL·E says: I am carrying the following items");
			System.out.println(robotContainer.toString());
			System.out.println("");
			}
		 else
		 {	
			if(!robotContainer.containsItem(itemToScan))
			throw new InstructionExecutionException("WALL·E says: I have not such object");			
			System.out.println("WALL·E says: " + robotContainer.getItem(itemToScan).toString());			
		 }
		}catch(Exception e){
			throw new InstructionExecutionException(e);
		}
	}
	
	public java.lang.String getHelp()
	{
		return ("SCAN | ESCANEAR [id]");
	}
	
	public void configureContext(RobotEngine engine,
            NavigationModule navigation,
            ItemContainer robotContainer)
	{
		this.robotContainer=robotContainer;
	}

}
